import Vue from "vue";
import Vuex from "vuex";
import serverInfo from './modules/server-info.js'

Vue.use(Vuex);

function getUserInfoFromLocal(){
	try{
		var str=window.localStorage.getItem("e-wallet-user");		
		if(str){
			var user=JSON.parse(str);
			if(user && user.username && user.token){
				return user;
			}else{
				return null;
			}
		}else{
			return null;
		}
	}catch(err){
		console.log("获取本地用户数据出错:"+err);
	}
}

//state
var state={
	user:getUserInfoFromLocal(),	
	lang:"en-US"   //默认值，这个键与用户业务的键要统一，这样用户切换语言时能带着ant design vue的国际化一起切换
}

//mutations
const mutations={
	setUser(state,user){
		state.user=user;
		try{
			window.localStorage.setItem("e-wallet-user",JSON.stringify(user));		
		}catch(error){
			console.log("设置城市数据出错,"+error);
		}
	},
	removeUser(state){
		window.localStorage.removeItem("e-wallet-user");	
		state.user={
			id:0,	
			birthDay: "",
			username: "",
			password: "",
			realName: "",
			registerDate: "",
			token: "",
			avator:""
		};		
		//window.location.href="/"
    },
    changeLang(state,payload){
        state.lang=payload;
    }
}

//actions
const actions={
    setLang(context,payload){
        context.commit("changeLang",payload);
    }
}

//getters:此处没有太多业务，仅仅是为了获取方便
const getters={
	getUser(){
		return state.user;
	},
	getLang(){
		return state.lang;
	}
};

export default new Vuex.Store({
    state:state,
    mutations: mutations,
    actions: actions,
    getters,
    modules: {
    	serverInfo
    }
});
